package com.tin.triper.Data;


import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class LocationProvider extends ContentProvider {

    public static final String PROVIDER_NAME = 
        "com.tin.provider.Trips";
    
    public static final Uri CONTENT_URI_LOCATION = 
        Uri.parse("content://"+ PROVIDER_NAME + "/locations");
    public static final Uri CONTENT_URI_TRIPS = 
        Uri.parse("content://"+ PROVIDER_NAME + "/trips");
    public static final Uri CONTENT_URI_RESOURCES = 
        Uri.parse("content://"+ PROVIDER_NAME + "/resources");
    
    public static final String LOCATION_ID = "location_id";
    public static final String LOCATION_LATITUDE = "latitude";
    public static final String LOCATION_LONGITUDE = "longitude";
    public static final String LOCATION_ALTITUDE="altitude";
    public static final String LOCATION_TIME="time";
    
    public static final String TRIP_ID="trip_id";
    public static final String TRIP_NAME="trip_name";
    public static final String TRIP_LENGTH = "trip_length";
    public static final String TRIP_TIME = "trip_time";
    
    public static final String RESOURCE_ID="resource_id";
    public static final String RESOURCE_TYPE="resource_type";
    public static final String RESOURCE_DESCRIPTION = "resource_description";
    public static final String RESOURCE_FILENAME = "resource_filename";
    
    private static final int LOCATIONS = 1;
    private static final int LOCATION_ID_URI = 2;    
    private static final int TRIPS = 3;
    private static final int TRIP_ID_URI = 4; 
    private static final int RESOURCES = 5;
    private static final int RESOURCE_ID_URI = 6; 
    
    private static final UriMatcher uriMatcher;
    static{
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "locations", LOCATIONS);
        uriMatcher.addURI(PROVIDER_NAME, "locations/#", LOCATION_ID_URI);        
        uriMatcher.addURI(PROVIDER_NAME, "trips", TRIPS);
        uriMatcher.addURI(PROVIDER_NAME, "trips/#", TRIP_ID_URI);    
        uriMatcher.addURI(PROVIDER_NAME, "resources", RESOURCES);
        uriMatcher.addURI(PROVIDER_NAME, "resources/#", RESOURCE_ID_URI);    
    }
    //---for database use---
    private SQLiteDatabase tripsDB;
    private static final String DATABASE_NAME = "Trips";
    private static final String DATABASE_TABLE_LOCATIONS = "locations";
    private static final String DATABASE_TABLE_TRIPS = "trips";
    private static final String DATABASE_TABLE_RESOURCES = "resources";

    private static final int DATABASE_VERSION = 3;
    private static final String DATABASE_CREATE_LOCATIONS =
        "create table " + DATABASE_TABLE_LOCATIONS + 
        " ("+LOCATION_ID+" integer primary key, "+
        LOCATION_LATITUDE+" integer," +
        LOCATION_LONGITUDE+" integer," +
        LOCATION_ALTITUDE+" integer," +
        LOCATION_TIME+" text," +
        TRIP_ID	+" integer);";
    private static final String DATABASE_CREATE_TRIPS =
        "create table " + DATABASE_TABLE_TRIPS + 
        " ("+TRIP_ID+" integer primary key, "+
        TRIP_NAME+" text," +
        TRIP_TIME+" integer," +
        TRIP_LENGTH+" real);";
    private static final String DATABASE_CREATE_RESOURCES =
        "create table " + DATABASE_TABLE_RESOURCES + 
        " ("+RESOURCE_ID+" integer primary key, "+
        RESOURCE_TYPE+" integer," +
        RESOURCE_DESCRIPTION+" text," +
        LOCATION_ID+" integer," +
        TRIP_ID+" integer," +
        RESOURCE_FILENAME+" text);";
    
    private static class DatabaseHelper extends SQLiteOpenHelper 
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            db.execSQL(DATABASE_CREATE_TRIPS);
            db.execSQL(DATABASE_CREATE_LOCATIONS);
            db.execSQL(DATABASE_CREATE_RESOURCES);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, 
        int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE_LOCATIONS);
            db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE_TRIPS);
            db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE_RESOURCES);
            onCreate(db);
        }
    } 
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
        int count=0;
        switch (uriMatcher.match(arg0)){
            case LOCATIONS:
                count = tripsDB.delete(
                		DATABASE_TABLE_LOCATIONS,
                        arg1, 
                        arg2);
                break;
            case TRIPS:
                count = tripsDB.delete(
                		DATABASE_TABLE_TRIPS,
                        arg1, 
                        arg2);
                break;
            case RESOURCES:
                count = tripsDB.delete(
                		DATABASE_TABLE_RESOURCES,
                        arg1, 
                        arg2);
                break;
            default: throw new IllegalArgumentException("Unknown URI " + arg0);    
        }       
        getContext().getContentResolver().notifyChange(arg0, null);
        return count;
	}

	@Override
	public String getType(Uri uri) {
        switch (uriMatcher.match(uri)){
        //---get all contacts---
        case LOCATIONS:
            return "vnd.android.cursor.dir/vnd.tin.location ";
        //---get a particular contact---
        case LOCATION_ID_URI:                
            return "vnd.android.cursor.item/vnd.tin.location ";
        case TRIPS:
            return "vnd.android.cursor.dir/vnd.tin.trips ";
        //---get a particular contact---
        case TRIP_ID_URI:                
            return "vnd.android.cursor.item/vnd.tin.trips ";
        case RESOURCES:
            return "vnd.android.cursor.dir/vnd.tin.resources ";
        //---get a particular contact---
        case RESOURCE_ID_URI:                
            return "vnd.android.cursor.item/vnd.tin.resources ";
        default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);        
    } 
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
        //---add a new contact---
		long rowID=0;
		int uriType;
        switch (uriMatcher.match(uri)){
	        case LOCATIONS:
	        	uriType=LOCATIONS;
	        	rowID = tripsDB.insert(
	                    DATABASE_TABLE_LOCATIONS, 
	                    "", 
	                    values);
	        	break;
	        case TRIPS:
	        	uriType=TRIPS;
	        	rowID = tripsDB.insert(
	                    DATABASE_TABLE_TRIPS, 
	                    "", 
	                    values);
	        	break;
	        case RESOURCES:
	        	uriType=RESOURCES;
	        	rowID = tripsDB.insert(
	                    DATABASE_TABLE_RESOURCES, 
	                    "", 
	                    values);
	        	break;
	        default: throw new IllegalArgumentException("Unknown URI " + uri); 
        }
        //---if added successfully---
        if (rowID>0)
        {
            if(uriType==LOCATIONS){
            	Uri _uri = ContentUris.withAppendedId(CONTENT_URI_LOCATION, rowID);
                getContext().getContentResolver().notifyChange(_uri, null);    
                return _uri;  
            }else if(uriType==TRIPS){
            	Uri _uri = ContentUris.withAppendedId(CONTENT_URI_TRIPS, rowID);
                getContext().getContentResolver().notifyChange(_uri, null);    
                return _uri;  
            }else if(uriType==RESOURCES){
            	Uri _uri = ContentUris.withAppendedId(CONTENT_URI_RESOURCES, rowID);
                getContext().getContentResolver().notifyChange(_uri, null);    
                return _uri;  
            }                
        }        
        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
        Context context = getContext();
        DatabaseHelper dbHelper = new DatabaseHelper(context);
        tripsDB = dbHelper.getWritableDatabase();
        return (tripsDB == null)? false:true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
        int uriType;
        switch (uriMatcher.match(uri)){
	        case LOCATIONS:
	        	uriType=LOCATIONS;
	            sqlBuilder.setTables(DATABASE_TABLE_LOCATIONS);

	        	break;
	        case TRIPS:
	        	uriType=TRIPS;
	            sqlBuilder.setTables(DATABASE_TABLE_TRIPS);

	        	break;
	        case RESOURCES:
	        	uriType=RESOURCES;
	            sqlBuilder.setTables(DATABASE_TABLE_RESOURCES);

	        	break;
	        default: throw new IllegalArgumentException("Unknown URI " + uri); 
        }
    
        if (uriMatcher.match(uri) == LOCATION_ID_URI){
            sqlBuilder.appendWhere(LOCATION_ID + " = " + uri.getPathSegments().get(1)); 
            if (sortOrder==null || sortOrder=="")
                sortOrder = LOCATION_ID;
        }
        else if(uriMatcher.match(uri) == TRIP_ID_URI){
        	sqlBuilder.appendWhere(TRIP_ID + " = " + uri.getPathSegments().get(1)); 
        	if (sortOrder==null || sortOrder=="")
                sortOrder = TRIP_ID;
        }
        else if(uriMatcher.match(uri) == RESOURCE_ID_URI){
        	sqlBuilder.appendWhere(RESOURCE_ID + " = " + uri.getPathSegments().get(1)); 
        	if (sortOrder==null || sortOrder=="")
                sortOrder = RESOURCE_ID;
        }

        Cursor c = sqlBuilder.query(
        		tripsDB, 
                projection, 
                selection, 
                selectionArgs, 
                null, 
                null, 
                sortOrder);

        //---register to watch a content URI for changes---
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
        int count = 0;
        switch (uriMatcher.match(uri)){
	        case LOCATIONS:
	            count = tripsDB.update(
	            		DATABASE_TABLE_LOCATIONS,
	            		values,
	                    selection, 
	                    selectionArgs);
	            break;
	        case LOCATION_ID_URI:
	            count = tripsDB.update(
	            		DATABASE_TABLE_LOCATIONS,  
	            		values,
	            		LOCATION_ID + " = " + uri.getPathSegments().get(1) + 
	                        (!TextUtils.isEmpty(selection) ? " AND (" + 
	                            selection + ')' : ""), 
	                        selectionArgs);
	            break;
	        case TRIPS:
	            count = tripsDB.update(
	            		DATABASE_TABLE_TRIPS,
	            		values,
	                    selection, 
	                    selectionArgs);
	            break;
	        case TRIP_ID_URI:
	            count = tripsDB.update(
	            		DATABASE_TABLE_TRIPS, 
	            		values,
	                    TRIP_ID + " = " + uri.getPathSegments().get(1) + 
	                        (!TextUtils.isEmpty(selection) ? " AND (" + 
	                            selection + ')' : ""), 
	                        selectionArgs);
	            break;
	        case RESOURCES:
	            count = tripsDB.update(
	            		DATABASE_TABLE_RESOURCES,
	            		values,
	                    selection, 
	                    selectionArgs);
	            break;
	        case RESOURCE_ID_URI:
	            count = tripsDB.update(
	            		DATABASE_TABLE_RESOURCES, 
	            		values,
	                    RESOURCE_ID + " = " + uri.getPathSegments().get(1) + 
	                        (!TextUtils.isEmpty(selection) ? " AND (" + 
	                            selection + ')' : ""), 
	                        selectionArgs);
	            break;
            default: throw new IllegalArgumentException("Unknown URI " + uri);    
        }       
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

}
